import * as UserApi from '@/api/user'
import authority from '@/utils/authority'

const { token = '', name = '' } = authority.get() || {}

const user = {
  state: {
    token,
    name
  },

  mutations: {
    SET_USER: (state, payload) => {
      Object.entries(payload).forEach(([key, value]) => {
        state[key] = value
      })
    }
  },

  actions: {
    // 登录
    login({ commit }, userInfo) {
      return UserApi.login({
        username: userInfo.username.trim(),
        password: userInfo.password
        // eslint-disable-next-line
      }).then(({ admin: data }) => {
        data.is_admin = 1
        authority.set(data)

        commit('SET_USER', data)
        commit('SET_PERMISSION_ROUTER')
      })
    },

    // 登出
    logout({ commit }) {
      return UserApi.logout().then(() => {
        commit('SET_USER', {
          token: '',
          name: ''
        })
        authority.clear()
        window.location.reload()
      })
    }
  }
}

export default user
